package prosjekt;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 * A JPanel that displays the products not currently marked as 'ferig' in
 * the database.
 * @author Even OEstvold
 */
@SuppressWarnings("serial") //No plans to serialize this class
public class KokkPanel extends JPanel {
	/**A JTable containing the products*/
	private JTable ordreTable;
	/**The JScrollPan connected to <code>ordreTable</code>*/
	private JScrollPane sPane;
	/**The class responsible for handling the underlying logic*/
	private KokkLogikk logikk;
	
	/**<code>KokkPanel</code> constructor*/
	public KokkPanel() {
		super(new GridBagLayout());
		initGUI();
		
		logikk = new KokkLogikk(this);
		logikk.start();
	}
	
	/**Sets up the GUI*/
	private void initGUI() {
		GridBagConstraints c = new GridBagConstraints();
		setPreferredSize(new Dimension(1029,670));
		setSize(new Dimension(1029,670));
		
		ordreTable = new KokkTable();
		ordreTable.removeColumn(ordreTable.getColumnModel().getColumn(0));
		ordreTable.removeColumn(ordreTable.getColumnModel().getColumn(0));
		ordreTable.setBackground(getBackground());
		ordreTable.getTableHeader().setReorderingAllowed(false);
		ordreTable.getTableHeader().setResizingAllowed(false);
		ordreTable.addMouseListener(new MouseAdapter(){
			//double click a row to set it`s state to 'ferdig'
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount() == 2)
					removeSelectedRow();
			}
		});
		
		//Add scrollPane to ordreTable
		sPane = new JScrollPane(ordreTable);
		sPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		sPane.setBorder(null);
		sPane.setPreferredSize(new Dimension(getWidth(),getHeight()-40));
		sPane.getVerticalScrollBar().setUnitIncrement(15);

		JButton complete = new JButton("Ferdig for levering");
		complete.addActionListener(new ActionListener(){
			//removes selected rows
			@Override
			public void actionPerformed(ActionEvent e) {
					removeSelectedRow();
			}
		});
		
		//Add components
		c.gridx  = 0; 			c.gridy = 0; 			c.gridwidth = 3;	
		c.anchor = GridBagConstraints.PAGE_START;		add(sPane, c);
		
		c.gridx  = 2; 			c.gridy = 1; 			c.gridwidth = 1;	
		c.anchor = GridBagConstraints.PAGE_END;			add(complete, c);
	}
	
	/**
	 * Adds an order to be displayed in this KokkPanel
	 * 
	 * @param ordreID -int, This orders ordreID
	 * @param produktID -int This orders productrID
	 * @param Nr -int, This orders menu.nr.
	 * @param navn -String, This orders menu.navn
	 * @param komentar -String, This orders komentar
	 */
	public void addOrdre(int ordreID,int produktID, int Nr, 
			String navn, String komentar, boolean ferdig){
		
		DefaultTableModel tm = (DefaultTableModel) ordreTable.getModel();
		tm.addRow(new Object[]{ordreID, produktID, Nr, navn, komentar, ferdig});
	}
	
	/**Removes all the products from this panel`s display*/
	public void removeAllProducts() {		
		for (int j = ordreTable.getRowCount()-1; j >= 0; j--) {
			((DefaultTableModel)ordreTable.getModel()).removeRow(j);
		}
	}
	
	/**
	 * Removes the given rows from the table and setting the state for 
	 * the selected elements to FINISHED.
	 * @throws SQLException 
	 */
	public void removeSelectedRow(){
		int[] a = ordreTable.getSelectedRows();
		int[] vID = new int[a.length];
		int[] oID = new int[a.length];

		//Get vareID and ordreID values
		for(int i = 0; i < a.length;i++){
			oID[i] = (Integer)ordreTable.getModel().getValueAt(a[i], 0);
			vID[i] = (Integer)ordreTable.getModel().getValueAt(a[i], 1);
		}

		//Set the state of the products in the database to finished
		for (int i = vID.length-1; i >= 0; i--) {
			try{
				RestaurantDB.setVareFerdig(vID[i]);
				ordreTable.getModel().setValueAt(true, a[i], 5);
				RestaurantDB.testAndSetOrdreFerdig(oID[i]);
			}catch (SQLException e) {
				//An error occurred while updating the database, the order will 
				//not be finished
			}
		}
	}
	


	/**
	 * A private JTable class used inside <code>KokkPanel</code> to display its
	 * orders.<p>
	 * 
	 * It contains six columns where the two first is hidden from view. They 
	 * exists to hold information to identify each row.
	 * 
	 * The columns are named as follow:
	 * <ol>
	 * 	<li>ordreID &nbsp&nbsp (hidden)
	 * 	<li>vareID &nbsp&nbsp&nbsp&nbsp (hidden)
	 * 	<li>Nr.
	 * 	<li>Navn
	 * 	<li>Kommentar
	 * 	<li>Ferdig
	 * </ol>
	 * 
	 * @author Even OEstvold
	 */
	private class KokkTable extends JTable{
		public KokkTable() {
			super();
			initGUI();
	    }
		
		/**Sets up the GUI*/
		private void initGUI() {
			KokkTableModel ktm = new KokkTableModel();
			//Name and add the columns
			ktm.addColumn("ordreID");	//order ID
			ktm.addColumn("vareID");	//product ID
			ktm.addColumn("Nr.");		//Product Nr.
			ktm.addColumn("Navn");		//Product name
			ktm.addColumn("Kommentar");	//Product comment
			ktm.addColumn("Ferdig");	//Product is 'ferdig'?
			
			//Set custom editor
			setModel(ktm);
			
			//Resize columns
			setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			getColumnModel().getColumn(2).setPreferredWidth(76);
			getColumnModel().getColumn(3).setPreferredWidth(200);
			getColumnModel().getColumn(4).setPreferredWidth(665);
			getColumnModel().getColumn(5).setPreferredWidth(65);
			
			setCellSelectionEnabled(false);
			setFillsViewportHeight(true);
			
			//Set a bigger font
			setFont(new Font(getFont().getName(),Font.PLAIN,25));
			setRowHeight(30);
		}

	    /**Shades alternate rows in different colors.*/
	    public Component prepareRenderer(TableCellRenderer renderer, 
	    		int row, int column) {
	    	
	        Component c = super.prepareRenderer(renderer, row, column);
	        
	        if(isRowSelected(row))	c.setBackground(getBackground().brighter());
	        else if (row%2==0)		c.setBackground(getBackground().darker());
	        else					c.setBackground(getBackground());
	        
	        return c;
	    }
	    
	    /**
	     * A private inner class used by <code>KokkTable</code> to disable 
	     * cell editing and display objects.
	     * @author Even OEstvold
	     */
	    private class KokkTableModel extends DefaultTableModel{
			public KokkTableModel() {
				super();
			}
			
			/**
			 * The Class representation of the given column. Returns 
			 * Object.class except on columnIndex = 5, when Boolean.class is
			 * returned.
			 * 
			 * @param columnIndex -int, the column to query
			 * @return Class -the class of the column being queried 
			 * */
			@Override
			public Class<?> getColumnClass(int columnIndex) {
				//Display column 5 as JCheckBox
				if(columnIndex == 5)
					return Boolean.class;
				return Object.class;
			}
			
			/**Returns false regardless of parameter values. */
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		}
	}
}


